<?php
namespace home\controllers;

use common\members\wodrow\components\gaode\WebService;
use common\models\db\User;
use common\models\db\UserOperateLog;
use home\models\FormEmailActiveLinkResend;
use home\models\FormLogin;
use home\models\FormResetPassword;
use home\models\FormSignup;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\ErrorAction;


class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only' => ['logout', 'signup', 'login', 'resend-active-link-for-email', 'reset-password', 'do-reset-password'],
                'rules' => [
                    [
                        'actions' => ['signup', 'login', 'resend-active-link-for-email', 'reset-password', 'do-reset-password'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
//                'fixedVerifyCode' => YII_ENV!=YII_ENV_PROD ? 'test' : null,
            ],
            'error' => [
                'class' => ErrorAction::class,
            ],
        ];
    }

    public function actionTest()
    {
        return $this->render('test1');
    }

    public function actionIndex()
    {
        /*\Yii::$app->timer->start();
        \Yii::$app->timer->point();
        \Yii::$app->timer->end();
        dump(\Yii::$app->timer->getRecords());
        dump(\Yii::$app->gaode_web_service->getLiveWeather('杭州'));*/
        return $this->render('index');
    }

    public function actionApiHelperDoc()
    {
        return $this->render('api-helper-doc1');
    }

    public function actionAbout()
    {
        return $this->render('about');
//        return $this->render('index1');
    }

    public function actionChat()
    {
        return $this->render('chat');
    }

    public function actionSignup()
    {
        $form_signup = new FormSignup();
        if ($form_signup->load(\Yii::$app->request->post())) {
            if ($user = $form_signup->signup()) {
                \Yii::$app->session->setFlash('success', "注册成功，请去邮箱激活账号");
                return $this->redirect(['site/login']);
            }
        }
        return $this->render('signup', [
            'form_signup' => $form_signup,
        ]);
    }

    public function actionActiveEmail($email, $code)
    {
        $params = \Yii::$app->params;
        $user = User::findOne(['email' => $email]);
        if (!$user){
            \Yii::$app->session->setFlash("error", "没有这个邮箱的账户，请注册！");
            return $this->redirect(['site/signup']);
        }
        switch ($user->status){
            case $user::STATUS_ACTIVE:
                \Yii::$app->session->setFlash('info', "你的账号已经激活了！请登录。");
                return $this->redirect(['site/login']);
                break;
            case $user::STATUS_EMAIL_UNACTIVE:
                if ($user->validateCode($code)){
                    $user->status = $user::STATUS_ACTIVE;
                    if ($user->save()){
                        \Yii::$app->session->setFlash('success', "激活成功！请登录。");
                        return $this->redirect(['site/login']);
                    }else{
                        \Yii::$app->session->setFlash('error', "账号激活异常！请联系管理员{$params['adminEmail']}。");
                        return $this->redirect(['site/index']);
                    }
                }else{
                    \Yii::$app->session->setFlash('error', "链接已失效！请向你的注册邮箱重新发送激活链接。");
                    return $this->redirect(['site/resend-active-link-for-email', 'email' => $email]);
                }
                break;
            default:
                \Yii::$app->session->setFlash("error", "账号状态异常！请联系管理员{$params['adminEmail']}。");
                return $this->redirect(['site/signup']);
                break;
        }
    }

    public function actionResendActiveLinkForEmail($email = null)
    {
        if ($email){
            $user = User::findOne(['email' => $email]);
            if (!$user){
                \Yii::$app->session->setFlash("error", "没有这个邮箱的账户，请注册！");
                return $this->redirect(['site/signup']);
            }
            if ($user && $user->status == $user::STATUS_ACTIVE){
                \Yii::$app->session->setFlash('info', "你的账号已经激活了！请登录。");
                return $this->redirect(['site/login']);
            }
        }
        $form_resend_active_link_for_email = new FormEmailActiveLinkResend();
        $form_resend_active_link_for_email->email = $email;
        if ($form_resend_active_link_for_email->load(\Yii::$app->request->post())&&$form_resend_active_link_for_email->validate()) {

            return $form_resend_active_link_for_email->send();
        }
        return $this->render('resend-active-link-for-email', [
            'form_resend_active_link_for_email' => $form_resend_active_link_for_email,
        ]);
    }

    public function actionResetPassword()
    {
        $form_reset_password = new FormResetPassword();
        if ($form_reset_password->load(\Yii::$app->request->post())&&$form_reset_password->validate()) {
            return $form_reset_password->reset();
        }
        return $this->render('reset-password', [
            'form_reset_password' => $form_reset_password,
        ]);
    }

    public function actionDoResetPassword($email, $code)
    {
        $params = \Yii::$app->params;
        $user = User::findOne(['email' => $email]);
        if (!$user){
            \Yii::$app->session->setFlash("error", "没有这个邮箱的账户，请注册！");
            return $this->redirect(['site/signup']);
        }
        if ($user->status != $user::STATUS_ACTIVE){
            \Yii::$app->session->setFlash('error', "你的账号未激活了！请先激活。");
            return $this->redirect(['site/resend-active-link-for-email']);
        }
        if (!$user->validateCode($code, $user::RESET_PASSWORD_CODE_PRE)){
            \Yii::$app->session->setFlash('error', "链接已失效！请重新进行重置密码操作。");
            return $this->redirect(['site/reset-password']);
        }else{
            $password = $user->getCacheData($user::PASSWORD_STORE_PRE);
            if (!$password) {
                \Yii::$app->session->setFlash('error', "已过期！请重新进行重置密码操作。");
                return $this->redirect(['site/reset-password']);
            }
            $user->setPassword($password);
            if ($user->save()){
                \Yii::$app->session->setFlash('success', "密码重置成功！请用新密码登录。");
                return $this->redirect(['site/login']);
            }else{
                \Yii::$app->session->setFlash('error', "密码重置失败！请联系{$params['adminEmail']}。");
                return $this->redirect(['site/signup']);
            }
        }
    }

    /**
     * @param null $back_url
     * @return string|\yii\web\Response
     * @throws
     */
    public function actionLogin($back_url = null)
    {
        $form_login = new FormLogin();
        if ($form_login->load(\Yii::$app->request->post()) && $form_login->login()) {
//            (new UserOperateLog())->doLog();
            \Yii::$app->session->addFlash('success', "登陆成功");
            if ($form_login->back_url){
                return $this->redirect($form_login->back_url);
            }else{
                return $this->goBack();
            }
        }
        if ($back_url){
            $form_login->back_url = $back_url;
            return $this->renderPartial('login', [
                'form_login' => $form_login,
            ]);
        }else{
            return $this->render('login', [
                'form_login' => $form_login,
            ]);
        }
    }

    public function actionLogout()
    {
        \Yii::$app->user->logout();
        return $this->goHome();
    }
}
